#!/bin/bash

findDisplayVariable() {
    local flags="-h"
    local w_output=$(w $flags)
    local active_user=$(logname 2>/dev/null || echo "$USER")

    w | grep -qi 'FROM'
    if [ $? -ne 0 ]
    then
        flags="${flags}f"
    fi

    # display_var=$(echo "$(w $flags)" | tr -s " " | cut -d" " -f3 | grep -e "^:[0-9]\+" -e "[a-z]\+[0-9]*:[0-9]")

    # # Find the first non-empty display variable
    # for eachDisplayVar in $display_var
    # do
    #     if [ -n "$eachDisplayVar" ]
    #     then
    #         display_var=$eachDisplayVar
    #         return 0
    #     fi
    # done

    # Extract display variable for the current active user
    display_var=$(w $flags | tr -s " " | awk -v user="$active_user" '
        $1 == user && ($2 ~ /^:[0-9]/ || $3 ~ /^:[0-9]/) {
            if ($2 ~ /^:[0-9]/) print $2;
            else print $3;
            exit;
        }')

    if [ -n "$display_var" ]; then
        return 0
    fi

    return 1
}

installDependenciesForComputeInstances() {
    apt=$(command -v apt-get)
    yum=$(command -v yum)
    zypper=$(command -v zypper)

	if [ -n "$zypper" ]; then
		zypper install libXcomposite-devel, libXdamage-devel libXtst-devel libgtk-3-0 libasound2 -y
	elif [ -n "$apt" ]; then
		apt install libxcomposite-dev libxdamage-dev libxtst-dev libgtk-3-0 libasound2-dev libxss1 -y
	elif [ -n "$yum" ]; then
		yum install libXcomposite libXdamage libXtst gtk3 alsa-lib -y
	else
		echo "ERR Machine Type Check Failed, cannot install required dependencies"
	fi
}

launchApp() {
    local xorgCount=`ps -ef | grep -e 'Xorg\b' -e 'X\b' | wc -l`
    local waylandCount=`ps -ef | grep -e 'Xwayland\b' | wc -l`

    if [ "$1" = 'setup' ]
    then
        if [ "$xorgCount" -ge 2 ] || [ "$waylandCount" -ge 2 ]
        then
            echo "The host has GUI. Please run 'remotepc-host login' or 'remotepc-host deploy <deployment ID>' to configure the host for remote access."
            exit 1
        elif [ `whoami` = 'root' ]
        then
            echo Setting up CLI access
            installDependenciesForComputeInstances

            systemctl stop remotepc-host.service
            systemctl disable remotepc-host.service 1> /dev/null 2> /dev/null

            sed -i 's/APP=remotepc-host/APP=remotepc-cli/' /opt/remotepc-host/.config/service/remotepc-host.service
            cp /opt/remotepc-host/.config/service/remotepc-host.service /etc/systemd/system/remotepc-host.service
            rm -f /opt/remotepc-host/.service.json ~/.config/remotepc-host/.remotepc-host-all.json
            systemctl enable remotepc-host.service 1> /dev/null 2> /dev/null
            systemctl start remotepc-host.service 1> /dev/null 2> /dev/null
            echo 1 > /opt/remotepc-host/resources/setupComplete

            echo 'RemotePC Host is setup for CLI access. Please use deploy or login command to configure the host. Run "remotepc-host help" for other help options'
            exit 0
        else
            echo Please use sudo access and run again
            exit 1
        fi
    fi

    if [ "$xorgCount" -ge 2 ]
    then
        if [ -f "/run/user/$UID/gdm/Xauthority" ]
        then
            cp /run/user/$UID/gdm/Xauthority ~/.Xauthority
        elif [ -f "/run/user/$UID/.Xauthority" ]
        then
            cp /run/user/$UID/.Xauthority ~/.Xauthority
        fi

        findDisplayVariable
        if [ $? -eq 0 ]
        then
            # echo display var is $display_var
            # echo GUI is installed, launching remotepc-host
            env DISPLAY="$display_var" APP=remotepc-host NODE_NO_WARNINGS=1 MESA_NO_WARNINGS=1 /opt/remotepc-host/remotepc-host $@ --no-sandbox 2>/dev/null
        else
            # echo "Error: Display variable not found. Launching using systemd"
            systemctl --user daemon-reload &
            systemctl --user start remotepc-host-appUI.service &

            local myPid=$!
            # echo "systemctl launched with pid $!"
            wait $myPid
            while ! [ -f ~/.config/remotepc-host/sample.txt ]
            do
                sleep 0.2
                # echo sleeping
            done
            # echo 'display variable should be written'
            display_var=`cat ~/.config/remotepc-host/sample.txt`
            # echo "display variable is $display_var"

            env DISPLAY="$display_var" APP=remotepc-host NODE_NO_WARNINGS=1 MESA_NO_WARNINGS=1 /opt/remotepc-host/remotepc-host $@ --no-sandbox 2>/dev/null
        fi
    else
        if [ "$waylandCount" -ge 2 ]
        then
            echo Remote sessions are not supported for wayland
            exit 1
        elif ! [ -f '/opt/remotepc-host/resources/setupComplete' ]
        then
            echo GUI is not installed
            echo Please run 'sudo remotepc-host setup' to configure host for CLI access
            exit 1
        else
            APP=remotepc-cli ELECTRON_RUN_AS_NODE=1 NODE_NO_WARNINGS=1 /opt/remotepc-host/remotepc-host /opt/remotepc-host/resources/app.asar $@
        fi
    fi
}

launchApp $@
